package com.zhmsky.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhmsky.entity.Product;
import com.zhmsky.model.ResultMap;
import com.zhmsky.service.ProductService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

/**
 * @author zhmsky
 * @date 2021/12/9 16:47
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;
    @Autowired
    private ResultMap resultMap;

    /**
     * @return
     * @description 查询所有物资信息
     * @permission admin和user
     */
    @GetMapping("/list")
    @RequiresRoles(logical = Logical.OR, value = {"admin", "user"})
    public ResultMap getProducts() {
        List<Product> productList = productService.list();
        return resultMap.success().code(200).message(productList);
    }

    /**
     * @return
     * @description 添加物资
     * @permission damin和user
     */
    @GetMapping("/add")
    @RequiresRoles(logical = Logical.OR, value = {"admin", "user"})
    public ResultMap add() {
        Product product = new Product();
        product.setName("普通口罩");
        product.setModel("5个/包");
        product.setUnit("包");
        product.setRemark("急缺");
        product.setSort(6);
        product.setPNum(UUID.randomUUID().toString().replaceAll("-", ""));
        boolean b = productService.save(product);
        if (b) {
            return resultMap.success().code(200).message("物资添加成功！");
        } else {
            return resultMap.fail().code(400).message("物资添加失败!");
        }
    }

    /**
     * @param id 根据id删除
     * @return
     * @description 删除物资
     */
    @DeleteMapping("/deletePro")
    @RequiresRoles(logical = Logical.OR, value = {"admin", "user"})
    public ResultMap deletePro(@RequestParam("id") Integer id) {
        boolean b = productService.removeById(id);
        if (b) {
            return resultMap.success().code(200).message("物资删除成功!");
        } else {
            return resultMap.fail().code(400).message("物资删除失败!");
        }
    }

    /**
     * @description 分页查询
     * @param page  当前页面
     * @param pageSize 页面大小
     * @return
     */
    @GetMapping("/getProductByPage")
    @RequiresRoles(logical = Logical.OR, value = {"admin", "user"})
    public ResultMap getProductByPage(@RequestParam("currentPage") Integer page, @RequestParam("pageSize")
            Integer pageSize) {
        Page<Product> currentPage = new Page<>(page,pageSize);
        productService.page(currentPage);
        List<Product> productList = currentPage.getRecords();
        return resultMap.success().code(200).message(productList);
    }




}
